'''
非阻塞IO
'''
from socket import *
from time import *

log = open('my.log', 'a')
# 创建TCP套接字
sock = socket()
sock.bind(('0.0.0.0', 1210))
sock.listen(5)

# 设置为非阻塞
# sock.setblocking(False)
sock.settimeout(3)
while True:
    try:
        connfd, addr = sock.accept()
        print('Connect from ', addr)
    except BlockingIOError as e:
        # 说明现在没有客户端连接，做点不相关的事情
        msg = '%s:%s\n' % (ctime(), e)
        log.write(msg)
        log.flush()
        sleep(2)
    except timeout as e:
        # 说明现在没有客户端连接，做点不相关的事情
        msg = '%s:%s\n' % (ctime(), e)
        log.write(msg)
        log.flush()

    else:
        # 没有发生异常,做点和accept有关的事情
        data = connfd.recv(1024)
        print(data.decode())
